<template>
  <el-dialog title="选择编程题" :visible.sync="visible" width="900px" append-to-body>
    <div class="mb-4 mt--4">
      <el-input v-model="query.keyword" placeholder="搜索题目" style="width: 300px" @keyup.enter.native="handleSearch">
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>

    <vxe-table stripe auto-resize :loading="loading" :data="questionList" align="center">
      <vxe-table-column field="id" title="ID" width="80"></vxe-table-column>

      <vxe-table-column field="problemId" title="题目ID" width="120"></vxe-table-column>      

      <vxe-table-column field="title" title="标题" min-width="300" align="left">
      </vxe-table-column>

      <vxe-table-column title="操作" width="80" fixed="right">
        <template v-slot="{ row }">
          <span v-if="hasSelected(row.id)" class="text-gray-500">已选择</span>
          <el-button v-else type="text" size="mini" @click="handleSelect(row)">选择</el-button>
        </template>
      </vxe-table-column>
    </vxe-table>

    <div>
      <div class="flex-x justify-end mt-4 gap-4">
        <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="query.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

  </el-dialog>
</template>

<script>
import api from '@/common/api'

export default {
  name: 'ProblemSelectDialog',
  data() {
    return {
      visible: false,
      loading: false,
      questionList: [],
      total: 0,
      selectedIds: [],    // 已经选择过的题目id
      query: {
        keyword: '',
        currentPage: 1,
        limit: 10
      }
    }
  },
  methods: {
    // 打开对话框
    open(selectedIds) {
      this.visible = true
      this.selectedIds = selectedIds || []
      this.loadProblems()
    },
    // 加载题目列表
    loadProblems() {
      this.loading = true
      api.admin_getProblemList({
        keyword: this.query.keyword,
        page: this.query.currentPage,
        limit: this.query.limit
      }).then(res => {
        this.questionList = res.data.data.records
        this.total = res.data.data.total
      }).finally(() => {
        this.loading = false
      })
    },

    // 搜索
    handleSearch() {
      this.loadProblems()
    },
    // 选择题目
    handleSelect(row) {
      const {id} = row
      this.$emit('select', id) // 支持多选
      this.visible = false
    },
    handleSizeChange(val) {
      this.query.limit = val
      this.loadProblems()
    },
    handleCurrentChange(val) {
      this.query.currentPage = val
      this.loadProblems()
    },   
    hasSelected(id) {
      return this.selectedIds.includes(id)
    }
  }
}
</script>
